#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import sys
import os
import platform

def print_banner():
    """打印程序横幅"""
    banner = """
    ╔══════════════════════════════════════════════╗
    ║                                              ║
    ║   B站追番列表爬虫 - 依赖安装工具             ║
    ║                                              ║
    ╚══════════════════════════════════════════════╝
    """
    print(banner)

def check_pip():
    """检查pip是否可用"""
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "--version"], 
                             stdout=subprocess.DEVNULL, 
                             stderr=subprocess.DEVNULL)
        return True
    except:
        return False

def install_package(package):
    """安装指定的包"""
    print(f"正在安装 {package}...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        print(f"{package} 安装成功！")
        return True
    except subprocess.CalledProcessError:
        print(f"{package} 安装失败！")
        return False

def main():
    """主函数"""
    print_banner()
    
    print("欢迎使用B站追番列表爬虫依赖安装工具！")
    print("本工具将帮助你安装运行爬虫所需的所有依赖包。\n")
    
    # 检查操作系统
    system = platform.system()
    print(f"检测到操作系统: {system}")
    
    # 检查Python版本
    python_version = platform.python_version()
    print(f"Python版本: {python_version}")
    
    # 检查pip
    if not check_pip():
        print("错误: 未检测到pip。请先安装pip后再运行此脚本。")
        sys.exit(1)
    
    print("\n开始安装基本依赖...")
    
    # 基本依赖
    basic_packages = ["requests", "beautifulsoup4"]
    for package in basic_packages:
        if not install_package(package):
            print(f"警告: {package} 安装失败，程序可能无法正常运行。")
    
    print("\n是否安装导出功能所需的依赖？")
    print("注意: 这些依赖较大，安装可能需要一些时间。")
    choice = input("请输入 (y/n): ").strip().lower()
    
    if choice == 'y':
        print("\n开始安装导出功能依赖...")
        
        # 导出功能依赖
        export_packages = ["pillow"]
        
        # WeasyPrint在不同系统上的安装可能有额外要求
        if system == "Windows":
            print("\n在Windows上安装WeasyPrint需要GTK+。")
            print("请参考: https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#windows")
            print("安装GTK+后，我们将继续安装WeasyPrint。")
            input("按Enter键继续...")
        elif system == "Darwin":  # macOS
            print("\n在macOS上安装WeasyPrint可能需要额外的依赖。")
            print("建议使用Homebrew安装: brew install cairo pango gdk-pixbuf libffi")
        
        export_packages.append("weasyprint")
        
        for package in export_packages:
            if not install_package(package):
                print(f"警告: {package} 安装失败，导出功能可能无法使用。")
    
    print("\n依赖安装完成！")
    print("现在你可以运行 python main.py 来启动B站追番列表爬虫。")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n安装已被用户中断。")
        sys.exit(0)
    except Exception as e:
        print(f"\n安装过程中出错: {e}")
        sys.exit(1)